package com.gm.lib.net;

import android.content.Context;
import android.text.TextUtils;
import com.gm.common.utils.LogUtil;
import com.gm.common.utils.NetUtil;
import com.gm.common.utils.ResUtil;
import com.gm.lib.R;
import com.gm.lib.cache.CacheApi;
import com.gm.lib.model.GMRequestModel;
import com.gm.lib.model.ResultModel;
import com.gm.lib.utils.GMToastUtil;
import com.gm.lib.utils.Md5Util;
import com.gm.net.RequestType;
import com.gm.net.client.AbsRequestClient;
import com.gm.net.model.RequestModel;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 网络请求公共类
 * GMNetRequest.getInstance().post
 * Created by cx on 15/4/21.
 */
public class GMNetRequest extends AbsRequestClient {


    private static GMNetRequest INSTANCE = new GMNetRequest();

    private ArrayList<BasicHeader> mHeaders = new ArrayList<BasicHeader>();

    @Override
    protected void request(RequestModel requestModel) {
        super.request(requestModel);
    }

    public static GMNetRequest getInstance() {
        return INSTANCE;
    }


    public GMRequestModel getGMRequestModel() {
        GMRequestModel model = new GMRequestModel();
        //header
        model.headers = getCommonHeaders();
        //默认post
        model.requestType = RequestType.POST;
        return model;
    }


    public GMRequestParams getGMRequestParams(JSONObject jsonBody) {
        return new GMRequestParams(jsonBody);
    }


    /**
     * 有些请求不需要context。 但注意，不传context的请求无法取消
     *
     * @param absGMRequest
     * @param gmApiHandler
     */
    public void post(AbsGMRequest absGMRequest, GMApiHandler gmApiHandler) {

        post(null, absGMRequest, gmApiHandler);

    }

    public void get(Context _context, AbsGMRequest absGMRequest, GMApiHandler gmApiHandler) {
        requestCommon(_context, absGMRequest, RequestType.GET, gmApiHandler);
    }

    private void requestCommon(Context context, AbsGMRequest absGMRequest, RequestType _requestType, GMApiHandler gmApiHandler) {

        //将request转为 handler里需要的model
        GMRequestModel requestModel = getGMRequestModel();
        requestModel.requestType = _requestType;
        requestModel.context = context;
        requestModel.jsonCls = absGMRequest.getJsonCls();
        requestModel.url = absGMRequest.getUrl();
        requestModel.params = absGMRequest.getRequestParams();



        //定义字符
        gmApiHandler.gmRequestModel = requestModel;
        requestModel.asyncHttpResponseHandler = gmApiHandler;

        LogUtil.d("url = %s ", absGMRequest.getUrl());
        Header[] headers = requestModel.headers;
        if (headers != null && headers.length > 0) {
            for (Header header : headers) {
                if (header != null && !TextUtils.isEmpty(header.getValue())) {
                    LogUtil.d("header %s", header.toString());
                }
            }
        } else {
            LogUtil.d("header is null ");
        }


        try {

            //设置缓存用的key，要在这里弄。因为后面的getGMRequestParams 会拼上随机字符串。

            String cacheKey = absGMRequest.getUrl();
            if (requestModel.params == null) {
                LogUtil.d("params is null");
            } else {
                LogUtil.d("params = %s", requestModel.params.toString());
                cacheKey += requestModel.params.toString();
            }

            switch (absGMRequest.getCacheMode()) {
                case NO_CACHE:
                    absGMRequest.setKey(null);
                    break;
                case NO_NET_ONLY:

                    absGMRequest.setKey(Md5Util.strToMd5_32(cacheKey));
                    if (!NetUtil.checkNetwork(context)) {
                        //如果无网，直接读缓存
                        Object object = CacheApi.getInstance().readCache(absGMRequest.getKey());
                        if (object != null) {
                            //有缓存机制： 先显示缓存，再请求数据
                            GMToastUtil.showToast(R.string.error_no_net);
                            gmApiHandler.onGMSuccess(object);
                        } else {
                            //如果网络请求有问题并且无缓存，那是真真的失败了
                            gmApiHandler.onNetFail(new ResultModel(-1, ResUtil.getString(R.string.error_no_net)));
                        }
                        return;
                    }

                    break;
                case CACHE_FIRST:

                    absGMRequest.setKey(Md5Util.strToMd5_32(cacheKey));
                    Object object = CacheApi.getInstance().readCache(absGMRequest.getKey());
                    if (object != null) {
                        //有缓存机制： 先显示缓存，再请求数据
                        LogUtil.d(absGMRequest.getKey() + " load cache first");
                        gmApiHandler.onCacheData(object);
                    }
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //定义cache
        requestModel.key = absGMRequest.getKey();
        requestModel.cacheMode = absGMRequest.getCacheMode();

        request(requestModel);

    }

    /**
     * 通用的网络请求。封装好GMRequest ，回调handler
     *
     * @param context
     * @param absGMRequest
     * @param gmApiHandler
     */
    public void post(Context context, AbsGMRequest absGMRequest, GMApiHandler gmApiHandler) {
        requestCommon(context, absGMRequest, RequestType.POST, gmApiHandler);

//        ByteArrayEntity entity = null;
//
//        try {
//
//            //设置缓存用的key，要在这里弄。因为后面的getGMRequestParams 会拼上随机字符串。
//
//            switch (absGMRequest.getCacheMode()) {
//                case NO_CACHE:
//                    absGMRequest.setKey(null);
//                    break;
//                case NO_NET_ONLY:
//
//                    if (context == null) {
//                        context = GlobalContext.getContext();
//                    }
//                    absGMRequest.setKey(Md5Util.strToMd5_32(absGMRequest.getJsonObject().toString()));
//                    if (!NetUtil.checkNetwork(context)) {
//                        //如果无网，直接读缓存
////                        Object object = CacheUtil.get(context).getAsObject(absGMRequest.getKey());
//                        Object object = CacheApi.getInstance().readCache(absGMRequest.getKey());
//
//                        if (object != null) {
//                            //有缓存机制： 先显示缓存，再请求数据
//                            GMToastUtil.showToast(R.string.error_no_net);
//                            gmApiHandler.onGMSuccess(object);
//                        } else {
//                            //如果网络请求有问题并且无缓存，那是真真的失败了
//                            gmApiHandler.onNetFail(new ResultModel(-1, ResUtil.getString(R.string.error_no_net)));
//                        }
//                        return;
//                    }
//
//                    break;
//                case CACHE_FIRST:
//
//                    if (context == null) {
//                        context = GlobalContext.getContext();
//                    }
//                    absGMRequest.setKey(Md5Util.strToMd5_32(absGMRequest.getJsonObject().toString()));
//                    Object object = CacheApi.getInstance().readCache(absGMRequest.getKey());
//                    if (object != null) {
//                        //有缓存机制： 先显示缓存，再请求数据
//                        LogUtil.d(absGMRequest.getKey() + " load cache first");
//                        gmApiHandler.onCacheData(object);
//                    }
//
//                    break;
//            }
//
//
//            //拼装json字符串
//
//            GMRequestParams params = getGMRequestParams(absGMRequest.getJsonObject());
//            LogUtil.d("url = %s ", absGMRequest.getUrl());
//            LogUtil.d("params = %s", params);
//
//            entity = new ByteArrayEntity(params.toString().getBytes("UTF-8"));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        requestCommon(context, absGMRequest, entity, "application/json", gmApiHandler);

    }

    /**
     * 调用平台API的公共参数 必备
     *
     * @return
     */
    protected Header[] getCommonHeaders() {
//        uid
//        BasicHeader uidHeader = new BasicHeader("uid", "55d7e94d7d681d4e62402243");
//        //token
//        BasicHeader tokenHeader = new BasicHeader("token", "c0a193c0-4bd5-11e5-8922-7312cdc8e790");
//        //header里有 uida token
//        Header[] commonHeaders = new Header[]{uidHeader, tokenHeader};
//        return commonHeaders;

        Header[] commonHeaders = new Header[mHeaders.size()];
        for (int i = 0; i < mHeaders.size(); i++) {
            commonHeaders[i] = mHeaders.get(i);
        }
        return commonHeaders;

    }

    public void addHeader(String key, String value) {
        for (int i = 0; i < mHeaders.size(); i++) {
            BasicHeader header = mHeaders.get(i);
            if (header.getName() == key) {
                mHeaders.remove(i);
                break;
            }
        }
        mHeaders.add(new BasicHeader(key, value));
    }

}
